package com.jt.redis.auth.service;

import com.jt.redis.auth.feign.RemoteUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    @Autowired
    private RemoteUserService remoteUserService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username == null||username.length()==0){
            throw new UsernameNotFoundException("此用户不存在");
        }
        //使用用户名查用户信息
        com.jt.redis.auth.pojo.User user = remoteUserService.selectUserByUsername(username);
        //使用用户信息获取id，基于用户id查用户权限
        List<String> permissions = remoteUserService.selectUserPermissions(user.getId());
        log.info("permissions:{}",permissions);
//        String encodePassword = passwordEncoder.encode("123456");//基于用户名查询用户信息，这里使用假信息
        List<GrantedAuthority> authorityList =
                AuthorityUtils.createAuthorityList(permissions.toArray(new String[]{}));
        return new User(username, user.getPassword(), authorityList);
    }
}
